<template>
  <div :id="mapId" style="width: 100%; height: 100%;"></div>
</template>
<script>
// 地图
import 'leaflet/dist/leaflet.css';
import * as L from 'leaflet';
import './js/L.Polyline.SnakeAnim.js';
import '@geoman-io/leaflet-geoman-free';


import markerIcon from './img/marker-icon.png';
import qd from './img/qidian.png';
import zd from './img/zhongdian.png';
export default {
  props: ['mapId'],
  data () {
    return {
      mapId: this.mapId,
      mapCenter: [23.07973176244989, 113.31298828125],
      mapZoom: 8,
      mapMarkerNameList: {},
      mapPolyLineNameList: [],
      drawPolyLineLayer: [],
      drawCircleLayer: [],
      drawRectangleLayer: [],
      drawPolygonLayer: [],
      measurePolyLineTooltip: [],
      measurePolyLineLayer: [],
      measureCircleTooltip: [],
      measureCircleLayer: [],
      measureRectangleTooltip: [],
      measureRectangleLayer: [],
      measurement: {
        m: '米',
        km: '千米',
        m2: '平方米',
        km2: '平方千米'
      },
    }
  },
  mounted () {
    // 初始化地图
    this.mapInit();
  },
  methods: {
    // 初始化地图
    mapInit () {
      // 地图选项
      this.map = L.map(this.mapId, {
        zoomControl: false, // 隐藏缩放级别按钮
        attributionControl: false, // 隐藏右下角LOGO信息
        center: this.mapCenter, // 设置地图中心点
        zoom: this.mapZoom, // 初始化缩放级别
      });
      // 创建地图对象
      let layer = new L.TileLayer('http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}');
      // 添加图层到地图
      this.map.addLayer(layer);
    },

    // 点击获取地图经纬度信息
    mapLatLngClick () {
      this.map.on('click', function (e) {
        console.log('纬度：' + e.latlng.lat + '\n经度：' + e.latlng.lng)
      });
    },

    // 设置地图中心点
    mapCenterClick (obj) {
      this.map.setView(obj);
    },

    // 标记点
    mapMarker (obj) {
      if (obj.name) this.deleteMarker(obj.name);
      let markerName = obj.name ? obj.name : 'marker';
      let lat = obj.lat;
      let lng = obj.lng;
      let icon = {};
      if (obj.icon) {
        icon = L.icon({
          iconUrl: obj.icon.iconUrl,
          iconSize: obj.icon.iconSize,
        });
      }else {
        icon = L.icon({
          iconUrl: markerIcon,
          iconSize: [32, 32],
        });
      };
      if (obj.divIcon) {
        icon = L.divIcon({
          html: obj.divIcon.html,
          iconSize: obj.divIcon.iconSize,
          className: obj.divIcon.className,
          popupAnchor: obj.divIcon.popupAnchor,
        });
      }else {
        icon = L.icon({
          iconUrl: markerIcon,
          iconSize: [32, 32],
        });
      };
      this.mapMarkerNameList[markerName] = new L.Marker([lat, lng],{icon}).addTo(this.map);
      if (obj.text) {
        if (obj.text.show) {
          this.mapMarkerNameList[markerName].bindPopup(obj.text.content).openPopup();
        }else {
          this.mapMarkerNameList[markerName].bindPopup(obj.text.content);
        };
      };
      if (obj.click) {
        this.mapMarkerNameList[markerName].on('click', (e)=> {
          obj.click(obj)
        });
      };
    },

    // 普通轨迹
    mapPolyline (obj) {
      if (obj.name) this.deletePolyLine(obj.name);
      let polyLineName = obj.name ? obj.name : 'polyLineName';
      if (obj.color) obj.color = "#1882f8";
      this.mapPolyLineNameList[polyLineName] = L.polyline(obj.latList, {color: obj.color}).addTo(this.map);
      this.map.fitBounds(this.mapPolyLineNameList[polyLineName].getBounds());
    },

    // 带动画的轨迹
    mapPolyLineAnimation (obj) {
      if (obj.name) this.deletePolyLine(obj.name);
      let polyLineName = obj.name ? obj.name : 'polyLineAnimationName';
      this.mapPolyLineNameList[polyLineName] = L.polyline(obj.latList, {snakingSpeed: 200, color: obj.color}).addTo(this.map);
      this.map.fitBounds(this.mapPolyLineNameList[polyLineName].getBounds());
      this.mapPolyLineNameList[polyLineName].snakeIn();
      this.mapPolyLineNameList[polyLineName].on('snakestart snake snakeend', function (e){
        if (e.type == 'snakeend') {
          console.log("终点")
        };
      })
    },

    // 带标记点的动画轨迹
    mapPolyLineMarkerAnimation (obj) {
      let routeGroup = L.featureGroup().addTo(this.map);
      let polyLineList = {};
      let markerList = {};
      let latLng = obj.latList.length;
      let lableColor = obj.color;
      let htmlStr = '<div class="trsWaterRipple" style="background: '+ lableColor +';"></div>';
      for (let i = 0; i < latLng-1; i++) {
        if (i === 0) { // 起点
          markerList = new L.Marker(obj.latList[i], {
            icon: L.icon({
              iconUrl: qd,
              iconSize: [32, 32],
              iconAnchor: [16, 32],
            }),
          });
        }else {
          markerList = new L.Marker(obj.latList[i], {
            icon: L.divIcon({
              html: htmlStr,
              className: 'trsWaterRipples',
            }),
          });
        };
        // 添加到图层组
        polyLineList = new L.polyline([obj.latList[i],obj.latList[i+1]],{ color: obj.color, snakingSpeed: 2000});
        routeGroup.addLayer(markerList);
        if (latLng - i === 2) {
          routeGroup.addLayer(markerList = new L.Marker(obj.latList[latLng-1], {
            icon: L.icon({
              iconUrl: zd,
              iconSize: [32, 32],
              iconAnchor: [16, 32],
            })
          }));
        };
        routeGroup.addLayer(polyLineList);
      };
      routeGroup.addLayer(polyLineList);
      this.map.fitBounds(routeGroup.getBounds());
      routeGroup.snakeIn();
      this.mapPolyLineNameList.push(routeGroup);
    },

    // 画圆
    drawCircle() {
      this.map.on('pm:create', e => {
        this.eventOff('Circle');
        this.drawCircleLayer.push(e.layer);
        let objData = {
          list: e.layer,
          tyoe: 'Circle',
        };
        this.$emit('returnData', objData);
      });
      this.map.pm.enableDraw('Circle', {});
    },

    // 画线
    drawPolyLine() {
      this.map.on('pm:create', e => {
        this.eventOff('Line');
        this.drawPolyLineLayer.push(e.layer);
        let objData = {
          list: e.layer,
          tyoe: 'Rectangle',
        };
        this.$emit('returnData', objData);
      });
      this.map.pm.enableDraw('Line', {});
    },

    // 画矩形
    drawRectangle() {
      this.map.on('pm:create', e => {
        this.eventOff('Rectangle');
        this.drawRectangleLayer.push(e.layer);
        let objData = {
          list: e.layer,
          tyoe: 'Rectangle',
        };
        this.$emit('returnData', objData);
      });
      this.map.pm.enableDraw('Rectangle', {});
    },

    // 画多边形
    drawPolygon() {
      this.map.on('pm:create', e => {
        this.eventOff('Polygon')
        this.drawPolygonLayer.push(e.layer);
        let objData = {
          list: e.layer,
          tyoe: 'Polygon',
        };
        this.$emit('returnData', objData);
      });
      this.map.pm.enableDraw('Polygon', {});
    },

    // 显示圆
    circle(obj) {
      if(!obj.name) obj.name = 'circle';
      this.deletePolyLine(obj.name);
      this.mapPolyLineNameList[obj.name] = L.circle([obj.lat, obj.lng], {
        color: '#3388ff',
        fillColor: '#3388ff',
        fillOpacity: 0.2,
        radius: obj.radius
      }).addTo(this.map);
      if(obj.text){
        if(obj.text.show)
          this.mapPolyLineNameList[obj.name].bindPopup(obj.text.content).openPopup();
        else
          this.mapPolyLineNameList[obj.name].bindPopup(obj.text.content);
      };
    },

    // 显示多边形
    polygon(obj){
      if(!obj.name) obj.name = 'polygonName1';
      this.deletePolyLine(obj.name);
      this.mapPolyLineNameList[obj.name]=L.polygon(obj.latlng,{
        color: '#3388ff',
        fillColor: '#3388ff',
        fillOpacity: 0.2,
      }).addTo(this.map);
      if(obj.text){
        if(obj.text.show)
          this.mapPolyLineNameList[obj.name].bindPopup(obj.text.content).openPopup();
        else
          this.mapPolyLineNameList[obj.name].bindPopup(obj.text.content);
      }
    },

    // 删除标记点
    deleteMarker (markerName) {
      if (this.mapMarkerNameList[markerName]) {
        this.map.removeLayer(this.mapMarkerNameList[markerName]);
        delete this.mapMarkerNameList[markerName];
      };
    },

    // 删除所有坐标点
    deleteMarkerList() {
      for (let key in this.mapMarkerNameList) {
        this.map.removeLayer(this.mapMarkerNameList[key]);
        delete this.mapMarkerNameList[key];
      }
    },

    // 删除轨迹
    deletePolyLine (polyLineName) {
      if (this.mapPolyLineNameList[polyLineName]) {
        this.map.removeLayer(this.mapPolyLineNameList[polyLineName]);
        delete this.mapPolyLineNameList[polyLineName];
      };
    },

    // 删除所有轨迹
    deletePolyLineList() {
      for (let key in this.mapPolyLineNameList) {
        this.map.removeLayer(this.mapPolyLineNameList[key]);
        delete this.mapPolyLineNameList[key];
      }
    },

    // 移除图层方法
    removeMethods(layerType, layerTip) {
      layerType.forEach(layer => {
        this.map.removeLayer(layer);
      })
      layerType = [];
      if (layerTip) {
        layerTip.forEach(e => {
          if (e.layer) {
            e.layer.closeTooltip();
          }
        });
        layerTip = [];
      }
    },

    // 移除画线图层
    removeDrawPolyLine() {
      this.removeMethods(this.drawPolyLineLayer);
    },

    // 移除画矩形图层
    removeDrawRectangle() {
      this.removeMethods(this.drawRectangleLayer);
    },

    // 移除画圆图层
    removeDrawCircle() {
      this.removeMethods(this.drawCircleLayer);
    },

    // 移除画多边形图层
    removeDrawPolygon() {
      this.removeMethods(this.drawPolygonLayer);
    },

    // 移除测距图层
    removeMeasurePolyLine() {
      this.removeMethods(this.measurePolyLineLayer, this.measurePolyLineTooltip);
    },

    // 移除测圆图层
    removeMeasureCircle() {
      this.removeMethods(this.measureCircleLayer, this.measureCircleTooltip);
    },

    // 移除测矩形图层
    removeMeasureRectangle() {
      this.removeMethods(this.measureRectangleLayer, this.measureRectangleTooltip);
    },

    // 清除事件
    eventOff(drawType) {
      this.map.pm.disableDraw(drawType);
      this.map.off('pm:drawstart');
      this.map.off('pm:create');
      this.map.off('pm:vertexadded');
      this.drawing = false;
    },

    // 测距
    measurePolyLine() {
      this.map.on('pm:create', e => {
        this.eventOff('Line');
        this.measurePolyLineTooltip[this.measurePolyLineTooltip.length - 1].isFinished = true;
        this.measurePolyLineLayer.push(e.layer);
      });
      this.map.on('pm:drawstart', ({workingLayer}) => {
        workingLayer.on('pm:vertexadded', e => {
          let marker = L.marker(e.latlng);
          if (this.measurePolyLineTooltip.length == 0 || this.measurePolyLineTooltip[this.measurePolyLineTooltip.length - 1].isFinished) {
            marker.bindTooltip('起点', {direction: 'top', sticky: true, permanent: true});
            this.map.openTooltip(marker.getTooltip(), marker.getLatLng());
            this.measurePolyLineTooltip.push({layer: marker});
          } else {
            let distance = this.map.distance(this.measurePolyLineTooltip[this.measurePolyLineTooltip.length - 1].layer.getLatLng(), e.latlng);
            if (this.measurePolyLineTooltip[this.measurePolyLineTooltip.length - 1].lastDistance) {
              distance = distance + this.measurePolyLineTooltip[this.measurePolyLineTooltip.length - 1].lastDistance;
            }
            if (distance / 1000 >= 1) {
              distance = distance / 1000;
              marker.bindTooltip(distance.toFixed(2) + this.measurement.km, {
                direction: 'top',
                sticky: true,
                permanent: true
              });
            } else {
              marker.bindTooltip(distance.toFixed(2) + this.measurement.m, {
                direction: 'top',
                sticky: true,
                permanent: true
              });
            }
            this.map.openTooltip(marker.getTooltip(), marker.getLatLng());
            this.measurePolyLineTooltip.push({layer: marker, lastDistance: distance});
          }
        });
      });
      this.map.pm.enableDraw('Line');
    },

    // 测圆面积
    measureCircle() {
      this.map.on('pm:create', e => {
        this.eventOff('Circle')
        let marker = L.marker(e.layer._latlng);
        let radius = e.layer._mRadius;
        let area = radius * radius * Math.PI;
        let toolTip = (measure1, measure2) => {
          marker.bindTooltip('面积:' + area.toFixed(2) + measure1 + '<br>' + '半径:' + radius.toFixed(2) + measure2, {
            direction: 'center',
            sticky: true,
            permanent: true
          });
        }
        if (area / 1000000 >= 1) {
          area = area / 1000000;
          if (radius / 1000 >= 1) {
            radius = radius / 1000;
            toolTip(this.measurement.km2, this.measurement.km);
          } else {
            toolTip(this.measurement.km2, this.measurement.m);
          }
        } else {
          if (radius / 1000 >= 1) {
            radius = radius / 1000;
            toolTip(this.measurement.m2, this.measurement.km);
          } else {
            toolTip(this.measurement.m2, this.measurement.m);
          }
        }
        this.map.openTooltip(marker.getTooltip(), marker.getLatLng());
        this.measureCircleTooltip.push({layer: marker});
        this.measureCircleLayer.push(e.layer);
      });
      this.map.pm.enableDraw('Circle');
    },

    // 测矩形面积
    measureRectangle() {
      this.map.on('pm:create', e => {
        this.eventOff('Rectangle')
        var marker = L.marker(e.layer._latlngs[0][1]);
        let south_north = this.map.distance(e.layer._latlngs[0][0], e.layer._latlngs[0][1]);
        let east_west = this.map.distance(e.layer._latlngs[0][1], e.layer._latlngs[0][2]);
        let area = south_north * east_west;
        let toolTip = (measure1, measure2, measure3) => {
          marker.bindTooltip('面积：' + area.toFixed(2) + measure1 + '<br>' + '南北长度：' + south_north.toFixed(2) + measure2 + '<br>' + '东西长度：' + east_west.toFixed(2) + measure3, {
            direction: 'center',
            offset: [0, -10],
            permanent: true
          });
        }
        if (area / 1000000 >= 1) {
          area = area / 1000000;
          if (south_north / 1000 >= 1 && east_west / 1000 < 1) {
            south_north = south_north / 1000;
            toolTip(this.measurement.km2, this.measurement.km, this.measurement.m);
          } else if (south_north / 1000 < 1 && east_west / 1000 >= 1) {
            east_west = east_west / 1000;
            toolTip(this.measurement.km2, this.measurement.m, this.measurement.km);
          } else if (south_north / 1000 >= 1 && east_west / 1000 >= 1) {
            south_north = south_north / 1000;
            east_west = east_west / 1000;
            toolTip(this.measurement.km2, this.measurement.km, this.measurement.km);
          } else {
            toolTip(this.measurement.km2, this.measurement.m, this.measurement.m);
          }
        } else {
          if (south_north / 1000 >= 1 && east_west / 1000 < 1) {
            south_north = south_north / 1000;
            toolTip(this.measurement.m2, this.measurement.km, this.measurement.m);
          } else if (south_north / 1000 < 1 && east_west / 1000 >= 1) {
            east_west = east_west / 1000;
            toolTip(this.measurement.m2, this.measurement.m, this.measurement.km);
          } else if (south_north / 1000 >= 1 && east_west / 1000 >= 1) {
            south_north = south_north / 1000;
            east_west = east_west / 1000;
            toolTip(this.measurement.m2, this.measurement.km, this.measurement.km);
          } else {
            toolTip(this.measurement.m2, this.measurement.m, this.measurement.m);
          }
        }
        this.map.openTooltip(marker.getTooltip(), marker.getLatLng());
        this.measureRectangleTooltip.push({layer: marker});
        this.measureRectangleLayer.push(e.layer);
      });
      this.map.pm.enableDraw('Rectangle');
    },
  },
}
</script>

<style lang="scss">
.leaflet-popup {
  margin-bottom: 40px;
}
.leaflet-popup-content-wrapper {
  min-width: 400px;
  min-height: 200px;
  border-radius: 0;
}

/** 水波纹效果 **/
.trsWaterRipple{
  position: relative;
  width: 10px;
  height: 10px;
  color: #ffffff;
  border-radius: 50%;
  /*background: rgba(24,144,255, .6);*/
}
.trsWaterRipple:before {
  position: absolute;
  content: "";
  width: 100%;
  height: 100%;
  background: inherit;
  border-radius: inherit;
  animation: wave 2s ease-out infinite;
}
@keyframes wave {
  50%,75% {
    transform: scale(2.5,2.5);
  }
  80%,100% {
    opacity: 0;
  }
}
/** 虚线 **/
.dashLines {
  stroke-dasharray: 10;
  stroke: #1882f8;
}
</style>
